import Ext from './common/web_extension'

Ext.runtime.onInstalled.addListener((details) => {
    console.log('onInstalled', details);
});

Ext.runtime.onStartup.addListener(() => {
    console.log('onStartup');
});

Ext.runtime.onSuspend.addListener(() => {
    console.log('onSuspend');
});

Ext.runtime.onUpdateAvailable.addListener((details) => {
    console.log('onUpdateAvailable', details);
});


const panelUrl = Ext.runtime.getURL('panel/index.html')

// Ext.tabs.create({
//     url: panelUrl,
//     active: true,
//     pinned: true,
//     windowId: Ext.windows.WINDOW_ID_CURRENT,
// })

Ext.windows.create({
    state: 'minimized',
    type: 'popup',
    url: panelUrl,
});

const getActiveTab = async () => {
    return await new Promise((resolve) => {
        chrome.tabs.query({ active: true }, (tabs) => {
            resolve(tabs.filter((tab) => tab.url !== chrome.runtime.getURL('panel/index.html'))[0]);
        })
    })
}

Ext.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('onMessage', message, sender, sendResponse);

    switch (message.action) {
        case 'takeScreenshot': {
            getActiveTab().then((tab: any) => {
                Ext.tabs.captureVisibleTab(tab.windowId, { format: 'png' }, (dataUrl) => {
                    sendResponse({
                        action: `response_${message.action}`,
                        from: 'service_worker',
                        type: 'sendResponse',
                        status: 'success',
                        data: dataUrl
                    })
                })
            })

            break
        }
        case 'takeFullScreenshot': {
            getActiveTab().then(async (tab: any) => {
                try {
                    // 附加调试器到当前标签页
                    await chrome.debugger.attach({ tabId: tab.id }, "1.3");

                    // 发送Page.captureScreenshot命令，设置captureBeyondViewport为true
                    const data: any = await chrome.debugger.sendCommand({ tabId: tab.id }, "Page.captureScreenshot", {
                        format: "png",
                        captureBeyondViewport: true,  // 关键参数，截图超出视口
                        fromSurface: true
                    });

                    const dataUrl = `data:image/png;base64,${data.data}`;

                    // 关闭调试器
                    await chrome.debugger.detach({ tabId: tab.id });

                    sendResponse({
                        action: `response_${message.action}`,
                        from: 'service_worker',
                        type: 'sendResponse',
                        status: 'success',
                        data: dataUrl
                    })

                } catch (error: any) {
                    console.error('全屏截图失败:', error);
                    // 确保发生错误时也关闭调试器
                    if (error !== chrome.runtime.lastError) {
                        console.error('Unexpected error: ' + error.message);
                    }
                    // 尝试分离调试器
                    try {
                        await chrome.debugger.detach({ tabId: tab.id });
                    } catch (e) { }
                }
            })

            break
        }
        case 'PANEL_SELECT_AREA_ON_CURRENT_PAGE': {
            getActiveTab().then(async (tab: any) => {

                chrome.tabs.sendMessage(tab.id, {
                    action: 'SELECT_SCREEN_AREA'
                })
                sendResponse({
                    from: 'service_worker',
                    action:'response_PANEL_SELECT_AREA_ON_CURRENT_PAGE',
                    type: 'sendResponse',
                    status: 'success',
                    data: null
                })
            })

            break
        }

        default:
            sendResponse({
                from: 'service_worker',
                type: 'sendResponse',
                status: 'success',
                data: null
            })
    }

    return true
});